require 'capistrano/ext/multistage'

set :stages, %w(sudene_prd sudene_trn sudene_hml sudam_trn sudam_prd)
set :default_stage, "sudene_hml"

set :application, "sibf"
#TESTE
set(:deploy_to) {"/var/www/vhosts/sudamlife.co.cc/httpdocs"}
#set(:deploy_to) {"/home/#{application}/www"}
#set(:deploy_to) {"/var/www/#{application}/#{stage}"}
#!!!!!
set(:rails_env) {"#{stage}"}
#set :gemhome, "/home/sibf/.gem/ruby/1.8"

set :repository,  "https://teste-felippe.googlecode.com/svn/trunk/"
set :scm_username, "felippepipipe"
set :scm_password, "s9f5e8a5"
#set :repository,  "https://axon.repositoryhosting.com/svn/axon_sibf/trunk"
#set :scm_username, "readonly"
#set :scm_password, "r34d0nly"

#set :user, "sibf"
set :user, "lifecon"
set :use_sudo, false
set :password, "Lif55CoN"

set :keep_releases, 2

after "deploy", "deploy:cleanup"
after "deploy:update_code", "deploy:flex:symlink", "deploy:assets:symlink"
after "deploy:setup",       "deploy:flex:setup",   "deploy:assets:setup"

namespace :deploy do
  desc "Restart Application"
  task :restart, :roles => :app, :except => { :no_release => true } do
    run "touch #{current_path}/tmp/restart.txt"
  end

  desc "Tail the log files"
  task :tailog, :roles => :app do
    stream "tail -n 60 #{shared_path}/log/#{rails_env}.log"
  end

  namespace :assets do
    desc "Creates assets folder on shared dir"
    task :setup, {:roles => :app} do
      run "mkdir -p #{shared_path}/assets"
    end

    desc "Links application assets on shared dir"
    task :symlink, {:roles => :app, :except => {:no_release => true}} do
      run <<-CMD
        rm -rf #{latest_release}/assets && ln -s #{shared_path}/assets #{latest_release}/assets
      CMD
    end
  end

  namespace :flex do
    desc "Deploy Flex app via default method"
    task :default do
      transaction do
        via_dumb_copy
        symlink
      end
    end

    desc "Creates flex folder on shared dir"
    task :setup, {:roles => :app} do
      run "mkdir -p #{shared_path}/flex_files"
    end

    # FIXME HACK task pra corrigir bug na original: release_path -> current_path
    desc "Fixed Restfulx Recipe"
    task :symlink, {:roles => :app, :except => {:no_release=>true}} do
      run <<-CMD
        rm -rf #{latest_release}/public/bin && mkdir -p #{latest_release}/public && ln -s #{shared_path}/flex_files #{latest_release}/public/bin
      CMD
    end
  end

end

namespace :rake do
  task :default do
    task = ENV['TASK']
    run "cd #{current_path} && rake #{task} RAILS_ENV=#{rails_env}"
  end
end
